package ugroupservice

import (
	"sort"
	"vpn-management-server/logger"
	"vpn-management-server/src/dao/admindao"
	"vpn-management-server/src/dao/rgroupdao"
	"vpn-management-server/src/dao/ruledao"
	"vpn-management-server/src/dao/ugroupdao"
	"vpn-management-server/src/dao/userdao"
	"vpn-management-server/src/dao/whitelistdao"
	"vpn-management-server/src/model/ugroupmodel"
	"vpn-management-server/src/service/userservice"
)

func GetUGroupByAdminNameService(name string) *ugroupmodel.UGroup {
	if adminUser, ok := admindao.GetAdminByName(name); ok {
		return ugroupdao.GetUGroupByAdminID(adminUser.ID)
	}
	return nil
}

func GetUGroupIDByPhoneService(phone string) int {
	return whitelistdao.GetUGroupIDByPhone(phone)
}

func DeleteUGroupService(ugid int) error {

	var err error

	// TODO 删除用户组管理员
	if AID := ugroupdao.GetAdminIDbyUGroupID(ugid); AID == -1 {
		logger.Logger.Error("get adminID by ugroupID fail")
		return err
	} else {

		err = admindao.DeleteAdmin(AID)
		if err != nil {
			logger.Logger.Error("delete ugroup admin fail")
			return err
		}
	}

	// TODO 删除用户组
	err = ugroupdao.DeleteUGroupByID(ugid)
	if err != nil {
		logger.Logger.Error("delete ugroup fail")
		return err
	}
	// TODO 删除分配给用户组的规则组
	err = rgroupdao.DepriveAllRGroupFromUGroup(ugid)
	if err != nil {
		logger.Logger.Error("delete rgroup fail")
		return err
	}
	// TODO 删除分配给用户组的规则
	err = ruledao.DepriveAllRuleFromUGroup(ugid)
	if err != nil {
		logger.Logger.Error("delete rule fail")
		return err
	}
	// TODO 删除用户组创建的规则组
	userInfos := userdao.GetAllUserInfosByUGroupID(ugid)
	for _, userInfo := range userInfos {
		// TODO 删除用户组用户
		// TODO 删除分配给用户的规则
		// TODO 删除分配给用户的规则组
		err = userservice.DeleteUserService(userInfo.ID)
		if err != nil {
			logger.Logger.Error("delete user fail")
			return err
		}
	}

	return nil
}

func GetAllUGroupUserCountService() map[string]int {
	var UGroupUserMap = make(map[string]int)
	nameInfos := ugroupdao.GetAllUGroupNameInfos()
	sort.Slice(nameInfos, func(i, j int) bool {
		return nameInfos[i].ID < nameInfos[j].ID
	})
	for _, nameInfo := range nameInfos {
		count := userdao.GetUserCountByUGroupID(nameInfo.ID)
		UGroupUserMap[nameInfo.Name] = count
	}
	return UGroupUserMap
}
